<template>
  <div class="main">
    <div class="mapmain" id="map"></div>
    <div class="cleft">
      <pcd title="目录">
        <el-input
          v-model="state.filterText"
          style="width: auto; margin: 0 28px"
          placeholder="根据关键词搜索"
          :suffix-icon="Search"
        />
        <div class="r22">
          <el-tree
            ref="treeRef"
            style="max-width: 600px"
            class="filter-tree"
            :data="state.treedata"
            :props="defaultProps"
            default-expand-all
            show-checkbox
            :filter-node-method="filterNode"
            @change="handleCheckChange"
            node-key="id"
            :style="{ background: 'transparent' }"
            :default-checked-keys="state.trees"
          >
            <template #default="{ data }">
              <span :title="data.name">{{ data.name }}</span>
            </template>
          </el-tree>
        </div>
      </pcd>
    </div>
    <div class="ccenter">
      <!-- <pcdh title="选择标签">
        <div class="zdata">
          <div
            class="zdorg"
            v-for="(item, index) in state.tagdata.lt_tagGroup"
            :key="index"
          >
            <div
              class="zdorgtext"
              :style="'width:' + item.groupName.length * 16 + 'px'"
            >
              {{ item.groupName }}
            </div>
            <el-checkbox-group
              v-model="state.tags"
              @change="cameraDistributeOnMapByLevel"
            >
              <el-checkbox-button
                v-for="(tag, inx) in item.lt_tag"
                :key="inx"
                :value="tag.tagCode"
                :label="tag.tagLable"
                :disabled="tag.used == 0"
              >
              </el-checkbox-button>
            </el-checkbox-group>
            <br />
          </div>
        </div>
      </pcdh> -->
    </div>
    <div class="cright">
      <div class="xxInfoSty" v-if="state.switch == 0 && state.clist.length > 0">
        <div class="titSty2">
          <span>已选设备列表</span>
          <el-button type="primary" style="color: #fff" link @click="toonemm"
            >查看详情
            <el-icon :size="20">
              <CaretRight />
            </el-icon>
          </el-button>
        </div>
        <div class="nrSty">
          <div class="disSty2">
            <div class="btSty">设备名称</div>
            <div class="nrXqSty">
              <el-button link style="color: #ffffff" @click="state.clist = []"
                >清空选择</el-button
              >
            </div>
          </div>
          <div class="disSty" v-for="(item, index) in state.clist" :key="index">
            <div class="btSty">{{ item.deviceName }}</div>
            <div class="nrXqSty">
              <el-button type="primary" link @click="rmone(item)"
                >删除</el-button
              >
            </div>
          </div>
        </div>
      </div>
      <div
        class="xxInfoSty"
        v-if="
          state.switch == 0 &&
          state.info.orgTypeCode &&
          state.info.orgTypeCode != 'street'
        "
      >
        <div class="titSty">{{ state.info.orgName }}</div>
        <div class="nrSty">
          <div class="disSty" v-for="(item, index) in state.infos" :key="index">
            <div class="btSty">{{ item[0] }}</div>
            <div class="nrXqSty">{{ item[1] }}</div>
          </div>
        </div>
      </div>
      <div
        class="xxInfoSty"
        v-if="
          state.switch == 0 &&
          state.info.hasOwnProperty('deviceId') &&
          state.info.deviceId != null
        "
      >
        <div class="titSty">
          {{ state.info.deviceName }}
          <el-button type="primary" style="width: 80px" @click="addlist"
            >加入备选</el-button
          >
        </div>
        <!-- <div
          style="
            width: 300px;
            height: 170px;
            background-color: #f2f2f2;
            margin: 10px 20px;
          "
        ></div> -->
        <div class="nrSty">
          <div class="disSty">
            <div class="btSty">设备ID</div>
            <div class="nrXqSty">{{ state.info.deviceId }}</div>
          </div>
          <div class="disSty">
            <div class="btSty">设备类型</div>
            <div class="nrXqSty">
              {{ state.info.cameraType_paramDict_value }}
            </div>
          </div>
          <div class="disSty">
            <div class="btSty">设备品牌</div>
            <div class="nrXqSty">{{ state.info.manufacturerName }}</div>
          </div>
          <div class="disSty">
            <div class="btSty">所属单位</div>
            <div class="nrXqSty">{{ state.info.maintainOrgName }}</div>
          </div>
          <div class="disSty">
            <div class="btSty">标签</div>
            <div class="nrXqSty exlipse" style="width:calc(100% - 100px)" :title="state.info.tagLabels">{{ state.info.tagLabels }}</div>
          </div>
          <div class="disSty">
            <div class="btSty">经度</div>
            <div class="nrXqSty">{{ state.info.longitude }}</div>
          </div>
          <div class="disSty">
            <div class="btSty">纬度</div>
            <div class="nrXqSty">{{ state.info.latitude }}</div>
          </div>
          <div class="disSty">
            <div class="btSty">IP地址</div>
            <div class="nrXqSty">{{ state.info.cameraIpv4 }}</div>
          </div>
          <div>
            <el-button
              type="primary"
              style="
                margin-top: 10px;
                margin-left: 10px;
                width: 280px;
                background: #2263bf;
              "
              @click="toonem"
              >监控详情</el-button
            >
          </div>
        </div>
      </div>
    </div>

    <onem ref="refonem" :list="state.slist" class="onem" />
  </div>
</template>

<script setup>
import {
  getparamdictApi,
  exportCameraListApi,
  cameraDistributeOnMapByLevelApi,
  getOrgsOnTreeView,
  showTagGroupAndTag,
} from "@/api/mapvue.js";
import { watch } from "vue";
import "ol/ol.css";
import { Map, View } from "ol";
import { Vector as VectorSource } from "ol/source.js";
import { Vector as VectorLayer } from "ol/layer.js";
import Feature from "ol/Feature.js";
import Point from "ol/geom/Point.js";
import ImageWMS from "ol/source/ImageWMS.js";
import { Image as ImageLayer } from "ol/layer.js";
import WKT from "ol/format/WKT.js";
import pcd from "@/components/videoplan/pcd.vue";
import { Polygon } from "ol/geom";
import {
  Circle as CircleStyle,
  Fill,
  RegularShape,
  Stroke,
  Style,
  Text,
  Icon,
} from "ol/style.js";

import { Search } from "@element-plus/icons-vue";
// import organization from "./organization.vue";
// import tag from "./tag.vue";
import onem from "./onem.vue";

const state = reactive({
  map: null,
  //树相关变量
  trees: [],
  treedata: [],
  filterText: "",
  commIds: [], //社区
  residIds: [], //小区
  cameraIds: [], //摄像头
  Ids: [],
  //标签
  tagdata: [],
  tags: [],
  //选择列表
  cv: false,
  clist: [],
  switch: 0,
  tagdata: [],
  points: [],
  info: {},
  infos: [],
  paramdict: {},
  layer: null,
  mlayer: null,
  mlist: [],
  feature: null,
  lastZoom: 0,
  slist: [],
  oneshow: true,
});

const refonem = ref(null);
const toonem = () => {
  state.slist = [state.feature.getProperties()];
  refonem.value.show();
};
const toonemm = () => {
  state.slist = [...state.clist];
  refonem.value.show();
};
const rmone = (item) => {
  state.clist.splice(state.clist.indexOf(item), 1);
};
const addlist = () => {
  let has = state.clist.find(
    (item) => item.deviceId == state.feature.get("deviceId")
  );
  if (!has) {
    state.clist.push(state.feature.getProperties());
  }
};
const initMap = () => {
  // let wms = new ImageLayer({
  //   source: new ImageWMS({
  //     url: "bcd/wms",
  //     params: { LAYERS: "bcd", VERSION: "1.1.0" },
  //     ratio: 1,
  //     serverType: "geoserver",
  //   }),
  // });
  // state.map = new Map({
  //   target: "map",
  //   layers: [
  //     wms
  //   ],
  //   view: new View({
  //     projection: "EPSG:4326",
  //     center: [117.69538, 38.994973],
  //     zoom: 12,
  //     maxZoom: 21,
  //     minZoom: 10,
  //   }),
  // });
  state.map = new Map({
    layers: [
      new ImageLayer({
        source: new ImageWMS({
          url: "/geoserver/bcd/wms",
          params: { LAYERS: "bcd", VERSION: "1.1.0" },
          ratio: 1,
          serverType: "geoserver",
        }),
      }),
    ],
    target: "map",
    view: new View({
      center: [117.74256851451989, 39.00380206757584],
      projection: "EPSG:4326",
      maxZoom: 21,
      minZoom: 10,
      zoom: 11.7,
    }),
    controls: [],
  });
  state.map.on("click", function (evt) {
    getFeatureInfo(evt.pixel);
  });
};
const getFeatureInfo = function (pixel) {
  if (state.layer == null) return;
  state.layer.getFeatures(pixel).then(function (features) {
    //恢复原来的颜色
    if (state.feature != null) {
      state.feature.setStyle(PStyle(state.feature));
    }
    let feature = features.length ? features[0] : null;
    if (feature) {
      state.feature = feature;
      state.feature.setStyle(PStyle(state.feature, "#6b8efd"));
      state.info = state.feature.getProperties();
      let info = JSON.parse(state.info.orgDesc);
      state.infos = [];
      for (let key in info) {
        state.infos.push([key, info[key]]);
      }
    } else {
      if (state.feature != null) {
        state.feature.setStyle(undefined);
        state.feature = null;
      }
      state.info = {};
      state.infos = [];
    }
  });
};

const treeRef = ref(null);
watch(
  () => state.filterText,
  (val) => {
    treeRef.value.filter(val);
  }
);
const defaultProps = {
  children: "children",
  label: function (data, node) {
    return (
      data.name +
      (data.type != "camera"
        ? " (" + data.deviceCountCurrentAndSubLevel + ")"
        : "")
    );
  },
};
const getTree = async () => {
  let { data } = await getOrgsOnTreeView({ orgTreeId: "1867783592617316356" });
  state.treedata = [data || {}];
  //设置全选
  state.trees = [state.treedata[0].id];
  //首次监听树节点变化
  setTimeout(() => {
    handleCheckChange();
  }, 500);
};
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name?.includes(value);
};
const handleCheckChange = () => {
  let nodes = treeRef.value.getCheckedNodes();
  state.commIds = [];
  state.residIds = [];
  state.cameraIds = [];
  state.Ids = [];
  for (let data of nodes) {
    if (data.type == "comm") {
      //社区
      state.commIds.push(data.id);
      state.Ids.push(data.id);
    }
    if (data.type == "resid") {
      //小区
      state.residIds.push(data.id);
      state.Ids.push(data.id);
    }
    if (data.type == "camera") {
      //摄像头
      state.cameraIds.push(data.id);
    }
  }
  //获取标签:waittodo
  // getTag();
  //获取地图数据
  cameraDistributeOnMapByLevel();
};
const getTag = async () => {
  let { data } = await showTagGroupAndTag({
    orgIds: state.Ids,
    cameraIds: state.cameraIds,
  });
  state.tagdata = data || [];
  state.tags = [];
};

const PStyle = (f, color) => {
  let zoom = state.map.getView().getZoom();
  let code = f.get("orgTypeCode");
  let name = "";
  if (zoom < 15) {
    if (code != "comm") return null;
    else {
      name = f.get("orgName") + "(" + f.get("count") + ")";
    }
  } else if (zoom >= 15 && zoom < 17) {
    if (code != "resid") return null;
    else {
      name = f.get("orgName") + "(" + f.get("count") + ")";
    }
  } else if (zoom >= 17) {
    if (code != null) return null;
    else {
      name = f.get("deviceName");
    }
  }

  return new Style({
    image: new Icon({
      src: "/images/point2.png",
      scale: 0.5,
    }),
    text: new Text({
      text: ["\ue737", "20px iconfont", " " + name, "14px PingFangSC"],
      offsetY: -36,
      font: "9pt serif",
      placement: "point",
      fill: new Fill({
        color: "#ffffff",
      }),
      backgroundFill: new Fill({
        color: color ? color : "#4e618b",
      }),
      padding: [5, 5, 5, 5],
    }),
  });
};

//获取社区、小区、摄像头地图数据
const cameraDistributeOnMapByLevel = async () => {
  let { data } = await cameraDistributeOnMapByLevelApi({
    tagIds: state.tags,
    commIds: state.commIds,
    residIds: state.residIds,
    deviceIds: state.cameraIds,
  });
  state.points = [...data.lt_comm, ...data.lt_resid, ...data.lt_device];
  state.mlist = [...data.lt_resid];
  dolayer();
};
const color1 = [
  "#6EABFB",
  "#51F2DF",
  "#FF6CB1",
  "#987AFF",
  "#FFD416",
  "#43EE36",
];
const color2 = [
  "#6EABFB28",
  "#51F2DF28",
  "#FF6CB128",
  "#987AFF28",
  "#FFD41628",
  "#43EE3628",
];
const format = new WKT();
const dolayer = () => {
  let mfs = [];
  let inx = 0;
  for (let item of state.mlist) {
    if (item.geom)
      mfs.push(
        new Feature({
          geometry: new Polygon(JSON.parse(item.geom)[0]),
          ...item,
          colorinx: inx,
        })
      );
    inx++;
    if (inx > 5) inx = 0;
  }
  let mds = new VectorSource({
    projection: "EPSG:4326",
    features: mfs,
  });

  let fs = [];
  for (let item of state.points) {
    if (item.longitude && item.latitude) {
      fs.push(
        new Feature({
          geometry: new Point([item.longitude, item.latitude]),
          ...item,
        })
      );
    }
  }
  let ds = new VectorSource({
    projection: "EPSG:4326",
    features: fs,
  });

  if (state.mlayer != null) {
    state.map.removeLayer(state.mlayer);
  }
  if (state.layer != null) {
    state.map.removeLayer(state.layer);
  }

  state.mlayer = new VectorLayer({
    title: "mapMp",
    source: mds,
    style: function (f) {
      let zoom = state.map.getView().getZoom();
      let inx = f.get("colorinx");
      return zoom < 15
        ? null
        : new Style({
            fill: new Fill({
              color: color2[inx],
            }),
            stroke: new Stroke({
              color: color1[inx],
              lineDash: [4, 4, 4, 4],
              width: 2,
            }),
          });
    },
  });
  state.map.addLayer(state.mlayer);

  state.layer = new VectorLayer({
    title: "map01",
    source: ds,
    style: function (f) {
      return PStyle(f);
    },
  });
  state.map.addLayer(state.layer);
  setTimeout(() => {
    state.map.renderSync();
  }, 500);
};

async function exportCameraList(param) {
  let { data } = await exportCameraListApi({
    lt_orgId: state.orgIds,
    param,
  });
  console.log("cameraDistributeOnMapByLevelres", data.resString);
  let a = document.createElement("a");
  a.href = data.resString;
  a.target = "_blank";
  a.style.dispaly = "none";
  a.click();
  a.remove();
}

const getparamdict = async () => {
  let { data } = await getparamdictApi();
  state.paramdict = data;
};

onMounted(() => {
  initMap();
  getTree();
  // getparamdict();
});
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100%;
  position: relative;
}

.mapmain {
  width: 100%;
  height: 100%;
  position: relative;
}

.othermain {
  width: 100%;
  height: 100%;
  position: relative;
  margin-left: 0px;
}
.onem {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #fff;
  padding: 24px 65px 35px 42px;
  z-index: 222;
}
.cleft {
  position: absolute;
  left: 0;
  top: 0;
  width: auto;
  height: 100%;
  display: flex;
  flex-direction: row;
  //   background: #fff;
}
.ccenter {
  position: absolute;
  left: 340px;
  top: 0;
  width: auto;
  height: auto;
  display: flex;
  flex-direction: column;
}
.cright {
  position: absolute;
  right: 0;
  top: 0;
  width: auto;
  height: auto;
  display: flex;
  flex-direction: column;
  .xxInfoSty {
    margin-top: 20px;
    width: 342px;
    background: #ffffff;
    box-shadow: 3px 3px 6px 0px #bdcde6,
      -4px -3px 4px 0px rgba(255, 255, 255, 0.5);
    border-radius: 6px;
    padding-bottom: 10px;
    .titSty {
      height: 40px;
      background: #2263bf;
      border-top-left-radius: 6px;
      border-top-right-radius: 6px;
      padding: 10px 20px;
      font-weight: 500;
      font-size: 16px;
      color: #ffffff;
      line-height: 22px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .titSty2 {
      color: #ffffff;
      height: 40px;
      background: #2263bf;
      border-top-left-radius: 6px;
      border-top-right-radius: 6px;
      padding: 10px 20px;
      font-weight: 600;
      font-size: 16px;
      line-height: 22px;
      display: flex;
      justify-content: space-between;
    }
    .nrSty {
      background: #ffffff;
      padding: 10px 20px;
      font-weight: 400;
      font-size: 16px;
      color: #000000;
    }
    .disSty {
      display: flex;
      justify-content: space-between;
    }
    .disSty2 {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #2263bf;
      height: 36px;
      padding: 0 10px;
      .btSty {
        color: #ffffff;
      }
      .nrXqSty {
        color: #ffffff;
      }
    }
    .btSty {
      font-weight: 500;
      font-size: 14px;
      color: #58627b;
      line-height: 26px;
    }
    .nrXqSty {
      font-weight: 400;
      font-size: 14px;
      color: #58627b;
      line-height: 26px;
      text-align: right;
      font-style: normal;
    }
  }
}

.modes {
  width: 114px;
  height: 48px;
  cursor: pointer;
  border-radius: 6px;
  display: flex; /* 使用 Flexbox 布局 */
  justify-content: center; /* 水平居中 */
  align-items: center;
}

.modetext {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 16px;
  color: #000000;
  line-height: 22px;
}

.activemodetext {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 16px;
  color: #fefefe;
  line-height: 22px;
}

.active {
  background: #6e8dfb;
}
.r22 {
  //   height: calc(100% - 32px);
  height: 100%;
  overflow-y: auto;
}
.line {
  width: 265px;
  height: 1px;
  margin-left: 5px;
  margin-bottom: 5px;
  box-shadow: 1px 1px 2px 0px #ffffff;
  border: 1px solid #ccddf7;
}

.zdata {
  display: flex;
  flex-direction: row;
  width: calc(50vw - 100px);
  height: auto;
  /* justify-content: space-between; */
}

.zdorg {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding-left: 3px;
  align-items: center;
  width: auto;
}

.zdorgtext {
  font-family: PingFangSC, PingFang SC;
  font-weight: 600;
  font-size: 16px;
  color: #293555;
  line-height: 22px;
  text-align: left;
  font-style: normal;
  margin-right: 5px;
}

.hcontainer {
  margin: 0px 20px;
  width: 170px;
}
.hc0 {
  width: auto;
  height: 100%;
  border-radius: 12px;
  padding: 10px;
  background: linear-gradient(135deg, #e9effb 0%, #fbfcff 100%);
  box-shadow: 3px 3px 16px 0px rgba(159, 177, 206, 0.7),
    -4px -3px 10px 0px #ffffff;
  border: 1px solid #ffffff;
}
.hc00 {
  height: 100;
  box-shadow: 1px 1px 2px 0px #ffffff;
  border: 1px solid #ccddf7;
  border-radius: 8px;
  /* padding: 14px; */
}
.hr1 {
  height: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0px 0px 1px 0px #ffffff;
  margin: 10px;
}
.hr1l {
  font-weight: 600;
  font-size: 16px;
  color: #293555;
  margin-right: 10px;
}
</style>
